package com.hang.gymmanager.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hang.gymmanager.Enum.*;
import com.hang.gymmanager.entity.*;
import com.hang.gymmanager.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/4/1 19:16
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class PlaceUseTask {

    private final PlaceService placeService;
    private final PlaceUseRecordService placeUseRecordService;
    private final ActivityService activityService;
    private final CourseService courseService;
    private final CourseRecordService courseRecordService;

    // 每天0点执行
    @Scheduled(cron = "0 0 0 * * ?")
    //测试用的 这是十秒一次
    //@Scheduled(fixedRate = 10000)
    public void initNewPlaceRecord() {
        //要保存的记录
        List<PlaceUseRecordEntity> list = new ArrayList<>();
        //先循环6次代表6个场地，再循环三次代表三天
        //虽然写死6个场地，以防万一还是查一下数量
        Long aLong = placeService.getBaseMapper().selectCount(null);
        //6个场地
        for(int i=1;i<=aLong;i++){
            //把当前的开始和结束时间拿出来
            LocalDateTime startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
            LocalDateTime endTime = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).plusSeconds(-1);
            //7天
            for(int j = 1;j<=7;j++){
                //看当天是不是有记录了，有的话跳过，没的话构造加到list
                QueryWrapper<PlaceUseRecordEntity> wrapper = new QueryWrapper<>();
                wrapper.lambda().between(PlaceUseRecordEntity::getDay,startTime.toLocalDate(),endTime.toLocalDate());
                List<PlaceUseRecordEntity> placeUseRecordEntities = placeUseRecordService.getBaseMapper().selectList(wrapper);
                if(placeUseRecordEntities.size()>0){
                    continue;
                }
                LocalDateTime smallBegin = LocalDateTime.now().plusDays(j-1).withHour(7).withMinute(0).withSecond(0).withNano(0);
                LocalDateTime smallEnd = LocalDateTime.now().plusDays(j-1).withHour(8).withMinute(0).withSecond(0).withNano(0);
                //循环12个时段
                for (int k = 1;k<=12;k++){
                    smallBegin = smallBegin.plusHours(1);
                    smallEnd = smallEnd.plusHours(1);
                    PlaceUseRecordEntity entity = new PlaceUseRecordEntity();
                    entity.setPlaceId(i);
                    entity.setType(PlaceUseRecordTypeEnum.NONE.getValue());
                    entity.setStatus(PlaceUseRecordStatusEnum.FUTURE.getValue());
                    entity.setRelationId(-1);
                    entity.setStartTime(smallBegin.toLocalTime());
                    entity.setEndTime(smallEnd.toLocalTime());
                    entity.setDay(smallBegin.toLocalDate());
                    list.add(entity);
                }
            }
        }
        //写到表里面
        placeUseRecordService.saveBatch(list);
    }

    //代表每小时的01分执行定时任务，任务主要是将过期的场地记录占用置为不可选，返回给学生选的时候不可选
    @Scheduled(cron = "1 0 * * * ?")
    public void expiredRecords() {
        QueryWrapper<PlaceUseRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().le(PlaceUseRecordEntity::getDay, LocalDate.now())
                .le(PlaceUseRecordEntity::getEndTime,LocalDateTime.now());
        List<PlaceUseRecordEntity> list = placeUseRecordService.getBaseMapper().selectList(wrapper);
        list.stream().forEach(e->e.setStatus(PlaceUseRecordStatusEnum.FINISH.getValue()));
        placeUseRecordService.saveBatch(list);

    }


    //活动时间段状态动态更新
    @Scheduled(cron = "1 0 * * * ?")
    //@Scheduled(fixedRate = 10000)
    public void updateActivityStatus() {
        LocalDateTime now  = LocalDateTime.now();
        QueryWrapper<ActivityEntity> wrapper = new QueryWrapper<>();
        //进行中的
        wrapper.lambda().le(ActivityEntity::getStartTime,now)
                .ge(ActivityEntity::getEndTime,now);
        List<ActivityEntity> ings = activityService.list(wrapper);
        ings.stream().forEach(e->e.setStatus(ActivityStatusEnum.DOING.getValue()));
        activityService.saveOrUpdateBatch(ings);
        //已经结束的
        wrapper.clear();
        wrapper.lambda().lt(ActivityEntity::getEndTime,now);
        List<ActivityEntity> ends = activityService.list(wrapper);
        ends.stream().forEach(e->e.setStatus(ActivityStatusEnum.FINISH.getValue()));
        activityService.saveOrUpdateBatch(ends);

    }

    //课程动态更新
    @Scheduled(cron = "1 0 * * * ?")
    //@Scheduled(fixedRate = 10000)
    public void updateCourseStatus() {
        LocalDateTime now  = LocalDateTime.now();
        QueryWrapper<CourseEntity> wrapper = new QueryWrapper<>();
        //进行中的
        wrapper.lambda().le(CourseEntity::getStartTime,now)
                .ge(CourseEntity::getEndTime,now);
        List<CourseEntity> ings = courseService.list(wrapper);
        ings.stream().forEach(e->e.setStatus(CourseStatusEnum.DOING.getValue()));
        courseService.saveOrUpdateBatch(ings);
        //已经结束的
        wrapper.clear();
        wrapper.lambda().lt(CourseEntity::getEndTime,now);
        List<CourseEntity> ends = courseService.list(wrapper);
        ends.stream().forEach(e->e.setStatus(CourseStatusEnum.FINISH.getValue()));
        courseService.saveOrUpdateBatch(ends);

    }

    //课程小节动态更新
    @Scheduled(cron = "1 0 * * * ?")
    //@Scheduled(fixedRate = 10000)
    public void updateCourseRecordStatus() {
        LocalDateTime now  = LocalDateTime.now();
        QueryWrapper<CourseRecordEntity> wrapper = new QueryWrapper<>();
        //进行中的
        wrapper.lambda().le(CourseRecordEntity::getStartTime,now)
                .ge(CourseRecordEntity::getEndTime,now);
        List<CourseRecordEntity> ings = courseRecordService.list(wrapper);
        ings.stream().forEach(e->e.setStatus(CourseStatusEnum.DOING.getValue()));
        courseRecordService.saveOrUpdateBatch(ings);
        //已经结束的
        wrapper.clear();
        wrapper.lambda().lt(CourseRecordEntity::getEndTime,now);
        List<CourseRecordEntity> ends = courseRecordService.list(wrapper);
        ends.stream().forEach(e->e.setStatus(CourseStatusEnum.FINISH.getValue()));
        courseRecordService.saveOrUpdateBatch(ends);

    }

    //场地状态动态更新
    @Scheduled(cron = "1 0 * * * ?")
    //@Scheduled(fixedRate = 10000)
    public void updatePlaceStatus() {
        LocalDate nowDay = LocalDateTime.now().toLocalDate();
        LocalTime nowTime = LocalDateTime.now().toLocalTime();
        //拿出所有场地记录
        QueryWrapper<PlaceUseRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(PlaceUseRecordEntity::getDay,nowDay)
                .le(PlaceUseRecordEntity::getStartTime,nowTime)
                .ge(PlaceUseRecordEntity::getEndTime,nowTime);
        List<PlaceUseRecordEntity> records = placeUseRecordService.list(wrapper);
        //拿出所有场地
        List<PlaceEntity> placeEntities = placeService.list();
        records.stream().forEach(e->{
            for (PlaceEntity place : placeEntities){
                if(e.getPlaceId().equals(place.getPlaceId())){
                    if(e.getRelationId()!=-1){
                        place.setPlaceStatus(PlaceStatusEnum.BUSY.getValue());
                    }else {
                        place.setPlaceStatus(PlaceStatusEnum.LEISURE.getValue());
                    }
                }
            }
        });
        placeService.saveOrUpdateBatch(placeEntities);
    }
}
